import { useEffect, useState } from 'react'
import Taro, { useShareAppMessage, useShareTimeline } from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'
import { Grid } from '@taroify/core'
import { getWeather } from '@/api/auth'

import {
  LocationOutlined,
  ClockOutlined,
  CashierOutlined,
  DiscountOutlined,
  Exchange,
  Paid,
  BillOutlined,
  DesktopOutlined,
  PhotoOutlined,
  FireOutlined
} from '@taroify/icons'
import './index.scss'

// 定义工具列表
const tools = [
  {
    id: 'qrcode',
    name: '二维码工具',
    description: '生成和扫描二维码',
    icon: <PhotoOutlined />,
    path: '/pages-qrcode/index',
    category: 'utility',
    recommended: true
  },
  {
    id: 'daily-recipe',
    name: '每日吃什么',
    description: '智能推荐菜谱、食材选菜',
    icon: <FireOutlined />,
    path: '/pages-recipe/index',
    category: 'utility',
    recommended: true
  },
  {
    id: 'mfa-authenticator',
    name: 'MFA安全验证（一）',
    description: '为账户添加二次验证保护',
    icon: <Paid />,
    path: '/pages-mfa/index',
    category: 'security',
    recommended: true
  },
  {
    id: 'totp-generator',
    name: 'MFA安全验证（二）',
    description: '生成各类服务的动态验证码',
    icon: <Paid />,
    path: '/pages-totp-generator/index',
    category: 'security',
    recommended: true
  },
  {
    id: 'mbti-test',
    name: 'MBTI性格测试',
    description: '发现你的性格类型和特质',
    icon: <DesktopOutlined />,
    path: '/pages-mbti/index',
    category: 'assessment',
    recommended: true
  },
  {
    id: 'layoff-calculator',
    name: '裁员赔偿计算',
    description: '快速计算裁员或解除劳动合同的补偿金额',
    icon: <BillOutlined />,
    path: '/pages-layoff/index',
    category: 'calculation',
    recommended: true
  },
  {
    id: 'loan-calculator',
    name: '贷款计算器',
    description: '计算贷款利息、月供和总还款额',
    icon: <CashierOutlined />,
    path: '/pages-dk/index',
    category: 'calculation',
    recommended: true
  },
  {
    id: 'bmi-calculator',
    name: 'BMI健康指数',
    description: '计算BMI、基础代谢率和体脂率',
    icon: <DesktopOutlined />,
    path: '/pages-bmi/index',
    category: 'assessment',
    recommended: true
  },
  {
    id: 'calculator',
    name: '基础计算器',
    description: '执行基本的数学运算',
    icon: <DiscountOutlined />,
    path: '/pages-calculator/index',
    category: 'calculation'
  },
  {
    id: 'unit-converter',
    name: '单位换算工具',
    description: '转换长度、重量、体积等单位',
    icon: <Exchange />,
    path: '/pages-unit-converter/index',
    category: 'calculation'
  },
  {
    id: 'date-calculator',
    name: '日期计算器',
    description: '计算日期差异、添加或减去天数',
    icon: <ClockOutlined />,
    path: '/pages-date-calculator/index',
    category: 'calculation'
  }
]

// 工具分类
const recommendedTools = tools.filter((tool) => tool.recommended)
const securityTools = tools.filter((tool) => tool.category === 'security')
const assessmentTools = tools.filter((tool) => tool.category === 'assessment')
const calculationTools = tools.filter((tool) => tool.category === 'calculation')
const utilityTools = tools.filter((tool) => tool.category === 'utility')

// 检查是否今天已提交反馈
const checkFeedbackSubmitted = () => {
  try {
    const today = new Date().toISOString().split('T')[0]
    const lastSubmit = Taro.getStorageSync('lastFeedbackDate')
    return lastSubmit === today
  } catch (error) {
    console.error('检查反馈状态出错', error)
    return false
  }
}

const Index = () => {
  const [weatherData, setWeatherData] = useState(null)
  const [location, setLocation] = useState('')
  const [showFeedback, setShowFeedback] = useState(false)
  const [feedbackText, setFeedbackText] = useState('')
  const [isFeedbackSubmitting, setIsFeedbackSubmitting] = useState(false)
  const [currentTheme, setCurrentTheme] = useState('mint') // 默认薄荷绿主题
  const [showThemeGuide, setShowThemeGuide] = useState(false) // 是否显示主题引导

  // 切换主题
  const toggleTheme = () => {
    const newTheme = currentTheme === 'mint' ? 'cream' : 'mint'
    setCurrentTheme(newTheme)
    setShowThemeGuide(false)
    Taro.setStorageSync('has-seen-theme-guide', 'true')

    // 保存主题设置到本地存储
    Taro.setStorageSync('user-theme-preference', newTheme)

    // 为页面添加对应的类名
    if (process.env.TARO_ENV === 'h5') {
      // H5环境使用DOM API
      const page = document.querySelector('page') || document.body
      if (page) {
        page.classList.remove('theme-mint', 'theme-cream')
        page.classList.add(`theme-${newTheme}`)
      }
    } else {
      // 小程序环境通过全局样式类处理
      // 注意：小程序环境下主题切换需要通过页面状态控制样式，在节点上添加对应的类名
      Taro.nextTick(() => {
        // 触发重渲染并应用新主题
        setCurrentTheme(newTheme)
      })
    }
  }

  useEffect(() => {
    // 检查是否首次使用（显示主题引导）
    try {
      const hasSeenGuide = Taro.getStorageSync('has-seen-theme-guide')
      if (!hasSeenGuide) {
        // 延迟显示引导，等待页面加载完成
        setTimeout(() => {
          setShowThemeGuide(true)
          Taro.setStorageSync('has-seen-theme-guide', 'true')
        }, 1000)
      }
    } catch (error) {
      console.error('检查引导状态出错', error)
    }

    // 加载用户主题偏好
    try {
      const savedTheme = Taro.getStorageSync('user-theme-preference')
      if (savedTheme && (savedTheme === 'mint' || savedTheme === 'cream')) {
        setCurrentTheme(savedTheme)

        // 应用保存的主题（仅H5环境）
        if (process.env.TARO_ENV === 'h5') {
          const page = document.querySelector('page') || document.body
          if (page) {
            page.classList.remove('theme-mint', 'theme-cream')
            page.classList.add(`theme-${savedTheme}`)
          }
        }
      }
    } catch (error) {
      console.error('读取主题偏好出错', error)
    }

    // 检查今天是否已提交反馈
    const hasSubmitted = checkFeedbackSubmitted()
    console.log('今日已提交反馈:', hasSubmitted)
    Taro.requirePrivacyAuthorize({
      success: () => {
        getWeatherFn()
        console.log('授权成功')
      },
      fail: () => {
        console.log('授权失败')
      }
    })
  }, [])

  // 关闭主题引导
  const closeThemeGuide = () => {
    setShowThemeGuide(false)
    // 保存已经看过引导的记录
    Taro.setStorageSync('has-seen-theme-guide', 'true')
  }

  const getWeatherFn = async () => {
    try {
      // 检查缓存
      const now = new Date()
      const today = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`
      // 暂时注释掉未使用的变量
      const cachedData = Taro.getStorageSync('weatherData')
      const cachedDate = Taro.getStorageSync('weatherDate')
      // 修改判断逻辑，只要日期匹配就使用缓存
      if (cachedDate === today && cachedData) {
        setWeatherData(cachedData)
        setLocation(Taro.getStorageSync('locationName') || '')
        return
      }
      // 获取用户当前位置
      let locationParam = ''

      try {
        const locationRes = await Taro.getFuzzyLocation({
          type: 'gcj02'
          // isHighAccuracy: true,
          // highAccuracyExpireTime: 3000
        })
        console.log(locationRes)
        // const { latitude, longitude } = locationRes
        // 经纬度用英文逗号分隔
        locationParam = `${locationRes.longitude},${locationRes.latitude}`
        setLocation('当前位置')
        Taro.setStorageSync('locationName', '当前位置')
        // 尝试获取位置名称（如果支持逆地址解析）
        // try {
        //   // 根据平台选择不同的方式获取地址信息
        //   if (process.env.TARO_ENV === 'weapp') {
        //     // 微信小程序通过逆地址解析获取地址
        // const postStr = JSON.stringify({
        //   lon: locationRes.longitude,
        //   lat: locationRes.latitude,
        //   ver: 1
        // })
        // const reverseRes = await Taro.request({
        //   url: `https://api.newayz.com/location/hub/v1/track_poin?ts?access_k=PSlBsHZr1UCZbkEzRGnQ0z1pN7JrYNeb`,
        //   data: {
        //     location: locations,
        //     // postStr: JSON.stringify({ lon: locationRes.longitude, lat: locationRes.latitude, ver: 1 }),
        //     asset: '1'
        //   },
        //   method: 'POST'
        // })
        // console.log(reverseRes)
        // const reverseRes = await Taro.request({
        //   url: `https://api.tianditu.gov.cn/geocoder`,
        //   data: {
        //     postStr: JSON.stringify({ lon: locationRes.longitude, lat: locationRes.latitude, ver: 1 }),
        //     type: 'geocode',
        //     key: '1f2139636d3e269b2fb6a4242d42743e'
        //   },
        //   method: 'GET'
        // })
        // console.log(reverseRes)

        //     if (reverseRes.data && reverseRes.data.result) {
        //       const address = reverseRes.data.result.address_component.city || '当前位置'
        //       setLocation(address)
        //       Taro.setStorageSync('locationName', address)
        //     }
        //   }
        // } catch (err) {
        //   console.error('获取地址信息失败', err)
        // }
      } catch (err) {
        console.error('位置获取失败', err)
        // // 如果获取位置失败，使用默认位置（北京）
        // locationParam = '116.41,39.92'
        // setLocation('北京')
        // Taro.setStorageSync('locationName', '北京')
      }

      // 请求天气数据
      Taro.showLoading({
        title: '加载中...',
        mask: true
      })
      const res = await getWeather(locationParam)
      Taro.hideLoading()
      // const res = { code: '200', data: { location: { name: '北京' } } }
      if (res && res.code === '200') {
        // 确保数据中包含daily数组
        if (res.daily && Array.isArray(res.daily)) {
          // 如果API返回了位置名
          setLocation('当前位置')

          // 保存到状态，只保存天气数据部分
          setWeatherData(res)

          // 保存到缓存
          try {
            Taro.setStorageSync('weatherData', res)
            Taro.setStorageSync('weatherDate', today)
            console.log('已保存天气数据到缓存，日期为:', today)
            console.log('保存的数据:', JSON.stringify(res))
          } catch (err) {
            console.error('保存缓存失败:', err)
          }
        } else {
          console.error('天气数据格式不正确:', res)
          Taro.showToast({
            title: '获取天气数据格式错误',
            icon: 'none'
          })
        }
      } else {
        console.error('获取天气失败:', res)
        Taro.showToast({
          title: '获取天气数据失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('获取天气失败', error)
    }
  }
  const handleToolClick = (path) => {
    Taro.navigateTo({
      url: path
    })
  }

  // 打开反馈弹窗
  /* const openFeedback = () => {
    if (checkFeedbackSubmitted()) {
      console.log('今日已提交反馈，感谢您的参与')
      Taro.showToast({
        title: '今日已提交反馈，感谢您的参与',
        icon: 'none'
      })
      return
    }
    console.log('打开反馈弹窗')
    setShowFeedback(true)
  } */

  // 提交反馈意见
  const submitFeedback = async () => {
    if (!feedbackText.trim()) {
      Taro.showToast({
        title: '请输入反馈内容',
        icon: 'none'
      })
      return
    }

    setIsFeedbackSubmitting(true)

    try {
      const result = await Taro.cloud.callFunction({
        name: 'submitFeedback',
        data: {
          content: feedbackText,
          timestamp: new Date().getTime()
        }
      })

      if (result && result.result && result.result.success) {
        // 保存今日已提交状态
        const today = new Date().toISOString().split('T')[0]
        Taro.setStorageSync('lastFeedbackDate', today)

        Taro.showToast({
          title: '感谢您的反馈',
          icon: 'success'
        })
        setShowFeedback(false)
        setFeedbackText('')
      } else {
        throw new Error('提交失败')
      }
    } catch (error) {
      console.error('提交反馈失败', error)
      Taro.showToast({
        title: '提交失败，请稍后重试',
        icon: 'none'
      })
    } finally {
      setIsFeedbackSubmitting(false)
    }
  }

  // 分享给朋友
  useShareAppMessage(() => {
    return {
      title: '这个超强工具集让我效率翻倍！省时省力的生活必备神器🔥',
      path: '/pages/index/index',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-img.png'
    }
  })

  // 分享到朋友圈
  useShareTimeline(() => {
    return {
      title: '这个超强工具集让我效率翻倍！省时省力的生活必备神器🔥',
      query: '',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-img.png'
    }
  })

  // 通用工具分类组件
  const ToolCategory = ({ title, toolsList, isRecommended }) => (
    <View className={`tools-category ${isRecommended ? 'recommended-category' : ''}`}>
      <Text className='section-title'>{title}</Text>
      <Grid columns={isRecommended ? 3 : 2} gutter={isRecommended ? 12 : 20} className='tools-grid'>
        {toolsList.map((tool) => (
          <Grid.Item key={tool.id}>
            <View className='tool-card' onClick={() => handleToolClick(tool.path, tool.id)}>
              <View className='icon-box'>{tool.icon}</View>
              <Text className='tool-name'>{tool.name}</Text>
              <Text className='tool-desc'>{tool.description}</Text>
              <Button color='var(--primary-color)' size='small' block className='tool-button'>
                打开工具
              </Button>
            </View>
          </Grid.Item>
        ))}
      </Grid>
    </View>
  )

  return (
    <View className={`index-page theme-${currentTheme}`}>
      {/* 主题切换按钮 */}
      <View
        className={`theme-switcher ${showThemeGuide ? 'theme-switcher-highlight' : ''}`}
        onClick={toggleTheme}
        style={showThemeGuide ? { zIndex: 9999 } : {}}>
        {currentTheme === 'mint' ? (
          <Text className='switcher-text'>清新</Text>
        ) : (
          <Text className='switcher-text'>暖色</Text>
        )}
      </View>

      {/* 首次使用的主题引导提示 */}
      {showThemeGuide && (
        <View className='theme-guide-overlay' onClick={closeThemeGuide}>
          <View className='guide-content' onClick={(e) => e.stopPropagation()}>
            <Text className='guide-title'>温馨提示</Text>
            <Text className='guide-text'>不喜欢当前风格？点击左上角按钮可随时切换主题风格，让界面更符合你的喜好！</Text>
            <Button className='guide-button' onClick={closeThemeGuide}>
              我知道了
            </Button>
          </View>
        </View>
      )}

      <View className='header'>
        <Text className='title'>一站式解决方案</Text>
      </View>
      {/* 天气信息部分 */}
      {weatherData && weatherData.daily && Array.isArray(weatherData.daily) && weatherData.daily.length > 0 ? (
        <View className='weather-section'>
          <View className='weather-header'>
            <LocationOutlined />
            <Text className='location-name'>{location}</Text>
          </View>

          <View className='current-weather'>
            <View className='temp-info'>
              <Text className='current-temp'>{weatherData.daily[0].tempMax || '--'}</Text>
              <Text className='temp-unit'>°C</Text>
            </View>
            <Text className='weather-desc'>{weatherData.daily[0].textDay || '--'}</Text>
          </View>

          <View className='forecast-container'>
            {weatherData.daily.slice(0, 3).map((day, index) => (
              <View key={index} className='forecast-item'>
                <Text className='forecast-day'>{index === 0 ? '今天' : index === 1 ? '明天' : '后天'}</Text>
                <Text className='forecast-temp'>
                  {day.tempMin || '--'}°~{day.tempMax || '--'}°
                </Text>
                <Text className='forecast-text'>{day.textDay || '--'}</Text>
                <Text className='forecast-wind'>
                  {day.windDirDay || '--'} {day.windScaleDay || '--'}级
                </Text>
              </View>
            ))}
          </View>
        </View>
      ) : (
        <View className='weather-section weather-loading'>
          <Text className='weather-loading-text'>正在获取天气数据...</Text>
        </View>
      )}

      {/* 分类工具部分 */}
      <View className='tools-container'>
        {/* 推荐工具区域 */}
        <ToolCategory title='推荐工具' toolsList={recommendedTools} isRecommended />

        {/* 分类工具区域 */}
        <ToolCategory title='安全工具' toolsList={securityTools} />
        <ToolCategory title='测评工具' toolsList={assessmentTools} />
        <ToolCategory title='计算工具' toolsList={calculationTools} />
        <ToolCategory title='实用工具' toolsList={utilityTools} />
      </View>

      {/* 悬浮反馈按钮 */}
      {/* {checkFeedbackSubmitted() && (
        <View className='feedback-float-btn' onClick={openFeedback}>
          <Comment size='24' />
          <Text className='feedback-text'>反馈</Text>
        </View>
      )} */}

      {/* 反馈弹窗 */}
      {showFeedback && (
        <View className='feedback-modal'>
          <View className='feedback-content'>
            <View className='feedback-header'>
              <Text className='feedback-title'>意见反馈</Text>
            </View>
            <View className='feedback-body'>
              <textarea
                className='feedback-textarea'
                placeholder='请输入您的意见或建议...'
                value={feedbackText}
                onInput={(e) => setFeedbackText(e.detail.value)}
                maxLength={500}
              />
              <Text className='feedback-limit'>{feedbackText.length}/500</Text>
            </View>
            <View className='feedback-footer'>
              <Button className='feedback-cancel' onClick={() => setShowFeedback(false)}>
                取消
              </Button>
              <Button className='feedback-submit' onClick={submitFeedback} loading={isFeedbackSubmitting}>
                提交
              </Button>
            </View>
          </View>
          <View className='feedback-mask' onClick={() => setShowFeedback(false)} />
        </View>
      )}
    </View>
  )
}

export default Index
